package com.cjst.controller.sys;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cjst.controller.base.BaseController;
import com.cjst.pojo.sys.SysDept;
import com.cjst.pojo.sys.SysOffice;
import com.cjst.pojo.sys.SysUser;
import com.cjst.sdp.util.MapUtils;
import com.cjst.sdp.util.ZTreeNode;
import com.cjst.service.sys.SysDeptService;
import com.cjst.service.sys.SysOfficeService;
import com.cjst.sql.C;
import com.cjst.sql.Method;
import com.cjst.sql.WherePrams;
import com.cjst.util.json.ResultObj;

/**
 * 部门管理
 *
 * @author yj
 */
@Controller
@RequestMapping("/sys/sysDept")
public class SysDeptController extends BaseController {

    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private SysOfficeService officeService;

    /**
     * 查询数据
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("dept")
    public Object list(SysDept sysDept) {
        WherePrams wherePrams = Method.where("status", C.EQ, "1");
        if (sysDept != null) {
            if (StringUtils.isNotEmpty(sysDept.getFullname())) {
                wherePrams.and("fullname", C.LIKE, sysDept.getFullname());
            }
            if (StringUtils.isNotEmpty(sysDept.getOfficeId())&&!"0".equals(sysDept.getOfficeId())) {
                // 拼接父id查询
                /*WherePrams where = Method.where("status", C.EQ, "1");
                where.and("id", C.EQ, sysDept.getOfficeId(), "1");
                where.or("parentIds", C.LIKE, sysDept.getOfficeId(), "1");
                List<SysOffice> depts = officeService.list(where);
                String deptIds = "";
                for (int i = 0; i < depts.size(); i++) {
                    deptIds += "'";
                    deptIds += depts.get(i).getId();
                    deptIds += "'";
                    if (i < depts.size() - 1) {
                        deptIds += ",";
                    }
                }
                if (!"".equals(deptIds)) {
                    wherePrams.and("officeId", C.IN, deptIds);
                }*/
            	wherePrams.and("officeId", C.EQ, sysDept.getOfficeId());
            }
        }

        List<SysDept> depts = sysDeptService.list(wherePrams);
        List<Map<String, Object>> maps = new ArrayList<>();
        for (SysDept dept : depts) {
            Map<String, Object> deptMap = MapUtils.transBean2Map(dept);
            //判断当前选择的节点是否顶层节点，如果不是，就查询上级节点
            if (dept.getPid() != null && !"0".equals(dept.getPid())) {
                WherePrams where = Method.where("id", C.EQ, dept.getPid());
                SysDept pDept = sysDeptService.get(where);
                if (pDept != null) {
                    deptMap.put("pName", pDept.getFullname());
                } else {
                    deptMap.put("pName", "-");
                }
            } else {
                deptMap.put("pName", "-");
            }
            if (dept.getOfficeId() != null && !"0".equals(dept.getOfficeId())) {
                WherePrams where = Method.where("id", C.EQ, dept.getOfficeId());
                SysOffice office = officeService.get(where);
                if (office != null) {
                    deptMap.put("officeName", office.getSimplename());
                } else {
                    deptMap.put("officeName", "-");
                }
            } else {
                deptMap.put("officeName", "-");
            }
            maps.add(deptMap);
        }
        return maps;
        //return pageUtil.getDate();
    }

    /**
     * 详情页面
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @RequiresPermissions("dept")
    public String toDept() {
        return "system/dept/dept";
    }

    /**
     * 跳转到添加页面
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    @RequiresPermissions("dept_add")
    public String addDept() {
        return "system/dept/dept_add";
    }

    /**
     * 跳转到修改页面
     */
    @RequestMapping(value = "/update/{deptId}", method = RequestMethod.GET)
    @RequiresPermissions("dept_update")
    public String updateDept(@PathVariable String deptId, Model model) {
        WherePrams where = Method.where("id", C.EQ, deptId);
        SysDept dept = sysDeptService.get(where);
        if (dept != null) {
            Map<String, Object> deptMap = MapUtils.transBean2Map(dept);
            //判断当前选择的节点是否顶层节点，如果不是，就查询上级节点
            if (dept.getPid() != null && !"0".equals(dept.getPid())) {
                WherePrams wherePrams = Method.where("id", C.EQ, dept.getPid());
                SysDept pDept = sysDeptService.get(wherePrams);
                if (pDept != null) {
                    deptMap.put("pName", pDept.getFullname());
                } else {
                    deptMap.put("pName", "顶层");
                }
            } else {
                deptMap.put("pName", "顶层");
            }
            if (dept.getOfficeId() != null && !"0".equals(dept.getOfficeId())) {
                WherePrams wherePrams = Method.where("id", C.EQ, dept.getOfficeId());
                SysOffice office = officeService.get(wherePrams);
                if (office != null) {
                    deptMap.put("officeName", office.getSimplename());
                } else {
                    deptMap.put("officeName", "顶层");
                }
            }
            model.addAttribute("dept", deptMap);
        }
        return "system/dept/dept_edit";
    }

    /**
     * 保存添加
     */
    @RequestMapping(value = "/save/add", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("dept_add")
    public Object saveDept(SysDept sysDept, HttpServletRequest req){
    	if(sysDept == null) {
    		return new ResultObj(0, "参数传递错误，新增部门失败", null);
    	}
    	//所属公司
    	String officeId = sysDept.getOfficeId();
    	if(StringUtils.isEmpty(officeId)) {
    		return new ResultObj(0, "参数【所属公司】未填写，新增部门失败", null);
    	}
    	SysOffice office = officeService.get(officeId);
    	if(office == null) {
    		return new ResultObj(0, "所属公司不存在，新增部门失败", null);
    	}
    	//上级部门
    	String pid = sysDept.getPid();
    	if(StringUtils.isEmpty(pid)) {
    		return new ResultObj(0, "参数【上级部门】未填写，新增部门失败", null);
    	}
    	//检查上级部门号并设置pid,pids
    	try {
    		setPids(sysDept);
		} catch (Exception e) {
			return new ResultObj(0, e.getMessage(), null);
		}
        sysDept.setStatus("1");
        String id =  sysDeptService.addLocalByid(sysDept);
        
        log.info("添加部门成功");
        return new ResultObj(1, "添加部门成功", id);
    }

    /**
     * 保存修改
     */
    @RequestMapping(value = "/save/update", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("dept_update")
    public Object saveUpdate(SysDept sysDept){
    	if(sysDept == null) {
    		return new ResultObj(0, "参数传递错误，修改部门失败", null);
    	}
    	//所属公司
    	String officeId = sysDept.getOfficeId();
    	if(StringUtils.isEmpty(officeId)) {
    		return new ResultObj(0, "参数【所属公司】未填写，修改部门失败", null);
    	}
    	SysOffice office = officeService.get(officeId);
    	if(office == null) {
    		return new ResultObj(0, "所属公司不存在，修改部门失败", null);
    	}
    	//上级部门
    	String pid = sysDept.getPid();
    	if(StringUtils.isEmpty(pid)) {
    		return new ResultObj(0, "参数【上级部门】未填写，修改部门失败", null);
    	}
    	try {
    		setPids(sysDept);
		} catch (Exception e) {
			return new ResultObj(0, e.getMessage(), null);
		}
        int i = sysDeptService.updateLocal(sysDept);
        log.info("修改部门成功");
        return new ResultObj(1, "修改部门成功", i);
    }

    /**
     * 保存删除,逻辑删除，删除该节点以及该节点的孩子节点
     */
    @RequestMapping(value = "/save/delete", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("dept_delete")
    public Object saveDelete(String deptId) {
    	if(StringUtils.isEmpty(deptId)) {
    		return new ResultObj(0, "参数传递错误，删除部门失败", null);
    	}
    	SysDept dept = sysDeptService.get(deptId);
    	if(dept == null) {
    		return new ResultObj(0, "部门不存在，删除失败", null);
    	}
    	
        WherePrams wherePrams = Method.where("id", C.EQ, deptId);
        wherePrams.or("pids", C.LIKE, deptId);
        SysDept dept2 = new SysDept();
        dept2.setStatus("0");
        int i = sysDeptService.updateLocal(dept2, wherePrams);
        return new ResultObj(1, "删除部门成功", i);
    }

    /**
     * 获取部门的tree列表
     */
    @RequestMapping(value = "/tree", method = RequestMethod.POST)
    @ResponseBody
    public List<ZTreeNode> tree(String officeId) {
    	SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        List<ZTreeNode> tree = sysDeptService.tree(officeId,sysUser);
        tree.add(ZTreeNode.createParent());
        return tree;
    }

    /**
     * 根据公司加载部门树
     */
    @RequestMapping(value = "/offTree", method = RequestMethod.POST)
    @ResponseBody
    public List<ZTreeNode> offTree() {
    	//加载公司树的时候，需要根据用户权限来查询展示
    	SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        List<ZTreeNode> tree = officeService.tree(sysUser,"-1");

        return tree;
    }


    private void setPids(@Valid SysDept dept) throws Exception {
        if (StringUtils.isEmpty(dept.getPid()) || "0".equals(dept.getPid())) {
            dept.setPids("0,");
        } else {
            String code = dept.getPid();
            //获取当前节点的父节点
            WherePrams where = Method.where("id", C.EQ, code);
            SysDept pDept = sysDeptService.get(where);
            if (pDept != null) {
                if (StringUtils.isNotEmpty(dept.getId()) && dept.getId().equals(pDept.getId())) {
                    throw new Exception("上级部门不能与当前部门相同");
                }
                if(StringUtils.isNotEmpty(dept.getId())  && pDept.getPids().contains(dept.getId())) {
                	throw new Exception("上级部门不能是当前节点的孩子节点");
                }
                dept.setPids(pDept.getPids() + pDept.getId() + ",");
            } else {
                throw new Exception("上级部门不存在");
            }
        }
        
        if(StringUtils.isNotEmpty(dept.getId())) {
        	 //查询数据库中该部门的信息,目前修改的部门信息还未更新到数据库
            SysDept dept2 = sysDeptService.get(dept.getId());
            
            //检查上级部门或者公司是否有变化
            if(!dept2.getPid().equals(dept.getPid())||!dept2.getOfficeId().equals(dept.getOfficeId())) {
            	//检查当前节点下是否有孩子节点
                WherePrams prams = Method.where("status", C.EQ, "1");
                prams.and("pids", C.LIKE, dept.getId());
                List<SysDept> depts = sysDeptService.list(prams);
                if(depts!=null&&depts.size()>0) {
                	for (SysDept sysDept : depts) {
        				//逐个遍历孩子节点，修改pids
                		String pids = sysDept.getPids();
                		//修改后的节点为用当前节点的父节点，替换原有节点的父节点
                		//例如0，1, 2 原有父节点1，直属孩子的父节点是2，现将当前节点的父节点替换成0，则pids为0,2 
                		pids = dept.getPids()+pids.substring(pids.indexOf(dept2.getPid())+dept2.getPid().length()+1);
                		
                		sysDept.setPids(pids);
                		sysDept.setOfficeId(dept.getOfficeId());
                		
                		sysDeptService.updateLocal(sysDept);
        			}
                }
            } 
        }
        
    }
    
    
    

    /**
     * 根据科室获取机构信息
     */
    @RequestMapping(value = "getOfficeByDept", method = RequestMethod.POST)
    @ResponseBody
    public Object getOfficeByDept(String deptId) throws Exception {
        //保存修改
        if (StringUtils.isEmpty(deptId)) {
            return new ResultObj(1, "参数传递异常", null);
        }
        WherePrams where = Method.where("id", C.EQ, deptId);
        SysDept dept = sysDeptService.get(where);
        if (dept != null) {
            SysOffice office = officeService.get(dept.getOfficeId());
            return new ResultObj(0, "成功", office);
        }
        return new ResultObj(0, "未查询所属机构", null);
    }

    /**
     * 通过部门id 获取当前id 已绑定机构
     */
    @RequestMapping(value = "getOfficeById", method = RequestMethod.POST)
    @ResponseBody
    public Object getOfficeById(String deptId) throws Exception {
        if (StringUtils.isEmpty(deptId)) {
            return new ResultObj(1, "参数传递异常", null);
        }
        WherePrams where = Method.where("id", C.EQ, deptId);
        SysDept dept = sysDeptService.get(where);
        if (dept != null) {
            SysOffice office = officeService.get(dept.getOfficeId());
            if (office != null) {
                return new ResultObj(0, "成功", office);
            }
            return new ResultObj(2, "未查询所属机构，查询异常", null);
        }
        return new ResultObj(1, "根据id未查询到相关信息，查询异常", null);
    }
    
    
    public static void main(String[] args) {
		String ids = "0,7CH0RUYA7HL4019WC6DAF0AAA11F42698854F58F45CC3929,TC78KX6WBRGZAP6I58E536CB550A42179E1F68760B5ABBA5,";
		System.out.println(ids.substring(ids.indexOf("7CH0RUYA7HL4019WC6DAF0AAA11F42698854F58F45CC3929")+"7CH0RUYA7HL4019WC6DAF0AAA11F42698854F58F45CC3929".length()+1));
	}
    
}
